package com.petter.lock.juc.countdownLatch;

import java.util.concurrent.CountDownLatch;

/**

 *
 * 写道题：实现一个容器，提供两个方法，add，size 写两个线程，
 * 线程1添加10个元素到容器中，
 * 线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束?
 * 使用CountDownLatch 代替wait notify 好处是通讯方式简单，不涉及锁定  Count 值为0时当前线程继续执行，
 *
 *
 * count i: 0
 * count i: 1
 * count i: 2
 * count i: 3
 * count i: 4
 * t2 is down
 * count i: 5
 * count i: 6
 * count i: 7
 * count i: 8
 * count i: 9
 *
 * @author : GD
 * @date :2021/12/21 : 22:09
 */
public class CountDownLatchForThread {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        new Thread(new CDLThread2(countDownLatch)).start();
        new Thread(new CDLThread1(countDownLatch)).start();
    }


}

class CDLThread1 implements Runnable{
    private CountDownLatch countDownLatch;

    public CDLThread1(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        try {
            countDownLatch.await();
            System.out.println("t2 is down");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class CDLThread2 implements Runnable{

    private CountDownLatch countDownLatch;

    public CDLThread2(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("count i: " + i);
            countDownLatch.countDown();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
